<template>
  <view class="exam">
    <uni-nav-bar :title="examPaperName" rightIcon="true">
    </uni-nav-bar>
    <block v-show="examObj">
      <scroll-view scroll-y class="scrollheight">
        <view class="main" @touchmove="handletouchmove" @touchstart="handletouchstart" @touchend="handletouchend">
          <view class="stem">
            {{examObj.topicTypeName}}
          </view>
          <uiTopic ref="topicRef" :optionData="optionData" :topicObj="examObj"></uiTopic>
        </view>
      </scroll-view>


      <view class="footer u-f-jsb u-f-ac">
        <view class="" @click="showBottomMask">
          <span class="iconfont icon-lunwentimu"></span>
          <text>(<span class="blue">{{current+1}}</span>/{{total}})</text>
        </view>
        <view class="u-f">
          <view class="prev btn marginright10" v-if="current+1>1" @click="toPrev">
            上一题
          </view>
          <view class="btn marginright10" v-if="current+1<total" @click="toNext">
            下一题
          </view>
          <view class="btn submit" v-show="optionData.length&&current+1==total" @click="submit">
            交卷
          </view>
        </view>

      </view>
      <uni-popup ref="popShare" type="center">
        <uni-popup-message title="提示" :message="tips" @close="close"></uni-popup-message>
      </uni-popup>
      <sliderBottom :show.sync="isBottomMask" :current.sync="current" :total="topicList.length"></sliderBottom>
    </block>
    <block v-if="topicList.length==0">
      <no-thing></no-thing>
    </block>
    <loading ref="loading" v-if="isloading"></loading>
  </view>
</template>

<script>
  import sliderBottom from '@/components/sliderBottom.vue'
  import uiTopic from '@/components/ui-topic.vue'
  import noThing from "@/components/comm/no-thing.vue"
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import {
    topicType
  } from '@/utils/model.js'
  export default {
    computed: { ...mapState(['isConnected', 'doTopicList', 'userInfo'])
    },
    components: {
      sliderBottom,
      uiTopic,
      noThing
    },
    data() {
      return {
        //显示底部侧栏选项
        isBottomMask: false,
        flag: 0,
        lastX: 0,
        lastY: 0,
        type: 0,
        current: 0,
        total: 0,
        topicList: [],
        optionData: [], //做题记录
        examPaperName: '',
        topicType,
        DestroyIncomeStatistics: true,
        examObj: {},
        isOver: true,
        isloading: true,
        tips: ''
      };
    },
    onLoad(option) {
      this.id = parseInt(option.id)
      uni.$on('saveOptionData', this.saveOptionData)
    },
    mounted() {
      this.getExamTopicList()
      
    },
    onBackPress(){
      // console.log('监听back1')
      return true
    },
    destroyed() {
      uni.$off('saveOptionData')
    },
    watch: {
      current: function(val) {
        this.getExamObj()
      }
    },
    methods: {
      ...mapMutations(['setDoTopicList']),
      getExamObj() {
        this.examObj = this.topicList.length > 0 ? this.topicList[this.current] : {}
      },
      // 保存做题记录
      saveOptionData(data) {
        // console.log(data, this.optionData)
        let id = this.examObj.id
        let obj = {
          "topicId": id,
          "option": "", //单选"B"   多选"A|B"
          "text": "", //简单文本之类
          "sort": 1,
          "topicRight": null,
          "score": "",
          ...data
        }
        let index = this.optionData.findIndex(item => item.topicId === id && item.sort === obj.sort)
        if (index > -1) { //已做过
          // 多选题
          if (this.topicType.checked === obj.topicTypeId) {
            console.log("多选")
            let options = this.optionData[index].option
            let optionIndex = options.indexOf(obj.option)
            // 多选题未选过
            if (optionIndex < 0) {
              this.optionData[index].option += ("|" + obj.option)
            } else {
              // 已选过只剩最后一个 则删除这题记录
              if (options.length == 1) {
                this.optionData.splice(index, 1)
              } else {
                switch (optionIndex) {
                  // 选第一选项
                  case 0:
                    this.optionData[index].option = options.substr(2)
                    break;
                  default:
                    this.optionData[index].option = options.replace('|' + obj.option, '')
                    break;
                }
              }
            }
            // 简答题
          } else if ([this.examObj.topicTypeId, obj.topicTypeId].includes(this.topicType.simple)) {
            if (obj.delImg) {
              this.optionData[index].text = this.optionData[index].text.replace(obj.text, '')
            } else {
              this.optionData[index].text += obj.text
            }

          } else {
            this.optionData.splice(index, 1, obj)
          }

        } else {
          //未做过
          this.optionData.push(obj)
        }
        // 混合题型与多选
        if ([this.topicType.multipleTopic, this.topicType.mixTopic].includes(this.topicList[this.current].topicTypeId)) {
          console.log('题型', this.topicList[this.current].topicTypeId, )

          this.$set(this.topicList[this.current].examPaperTopicDTOS[obj.sort - 1], 'optionData', this.optionData.filter(
            item => item.topicId === id && item.sort === obj.sort))
          //强制刷新组件
          // this.DestroyIncomeStatistics = false;
          //    this.$nextTick(() => {
          //           this.DestroyIncomeStatistics = true;
          //         });
          this.examObj = this.$utils.deepClone(this.topicList[this.current])

        } else {
          this.$set(this.topicList[this.current], 'optionData', this.optionData.filter(item => item.topicId === id))
          this.examObj = Object.assign({}, this.examObj, {
            optionData: this.optionData.filter(item => item.topicId === id)
          })

        }


        //完形填空存为数组类型
        console.log(this.optionData)
      },

      // 获取试卷题目
      async getExamTopicList() {
        let obj = this.doTopicList.find(item => item.id == this.id);
        // 已做过从缓存拿数据
        if (!this.isConnected && obj) {
          console.log(obj.topicList)
          this.total = obj.total
          this.examPaperName = obj.examPaperName
          this.topicList = obj.topicList
        } else if (this.isConnected) {
          let result = await this.$http.get(`/examPaper/${this.id}?mark=true`)
          // console.log(result) 
          this.examPaperName = result.data.examPaperName
          let testList = []
          result.data.models.forEach(item => {
            testList = [...testList, ...item.topics]
          })

          testList.forEach((item, index) => {
            item.optionData = []
            item.num = 0
            // item.title = item.topicTitle
            // item.topicTitle = item.topicTitle.replace(/(___[0-9]___)/g, '___')
            // 混合题型与多选
            if ([this.topicType.multipleTopic, this.topicType.mixTopic].includes(item.topicTypeId)) {
              item.examPaperTopicDTOS.forEach((obj, i) => {
                obj.optionData = []
                obj.num = i + 1

              })
            }
          })
          this.topicList = testList

          this.total = this.topicList.length
          this.topicList.length > 0 && this.setDoTopicList([{
            id: this.id,
            total: this.total,
            examPaperName: this.examPaperName,
            topicList: this.topicList
          }, 'update'])
        } else {
          this.$showToast('未联网无数据')
          this.topicList = []
        }
        this.isloading = false
        this.getExamObj()
        this.tips = `本专题练习包含${this.total}道题，提交后不能再重做。请合理安排时间，一次完成。`
        this.$refs.popShare.open()
      },
      // 点击显示底部选项遮罩层
      showBottomMask() {
        this.isBottomMask = !this.isBottomMask
      },
      // 交卷事件
      submit() {

        let flag = this.topicList.some(item => {
          // console.log(item.optionData)
          if ([this.topicType.multipleTopic, this.topicType.mixTopic, this.topicType.simple].includes(item.topicTypeId)) {
            if (this.optionData.filter(obj=>obj.topicId===item.id).length !== item.examPaperTopicDTOS.length) {
              return true
            }
          }
          if ([this.topicType.fill].includes(item.topicTypeId)) {
            if (item.optionData.length !== item.topicTitle.match(/(___[0-9]___)/g).length) {
              return true
            }
          }
          if ([this.topicType.cloze].includes(item.topicTypeId)) {
            if (item.optionData.length !== Object.keys(item.optionGroup).length) {
              return true
            }
          }
          if ([this.topicType.select, this.topicType.radio].includes(item.topicTypeId)) {
            if (item.optionData.length === 0) {
              return true
            }
          }
        })
        if (flag) {
          this.tips = '您有未答完的题,是否确认交卷'
        } else {
          this.tips = '确认答题结束?交卷后无法再次答题'
        }
        // if (!this.isOver) {
        //   this.$showToast('完形填空未填完')
        //   return false
        // }

        this.$refs.popShare.open()
      },
      async close(e) {
        // 判断是否是进页面提示
        if (this.tips.indexOf('提交后不能再重做') > -1) {
          if (!e.confirm) {
            this.$back()
          }
        } else {
          console.log(e)
          if (e.confirm) {
            //交卷操作
            // console.log(`?stuId=${this.userInfo.id}&&examPaperId=${this.id}`, this.optionData)
            let res = await this.$http.put(
              `/makeExamPaper/make?stuId=${this.userInfo.id}&&examPaperId=${this.id}`, this.optionData
            )
            if (res.status == 0) {
              this.$back()
            }
          }
        }

      },
      // 上一题
      toPrev() {
        if ((this.current + 1) <= 1) {
          return false;
        }
        this.current--;

      },
      // 下一题
      toNext() {
        if ((this.current + 1) >= this.total) {
          return false;
        }
        this.current++;

      },
      // 上下滑动/左右滑动
      handletouchmove: function(event) {
        // console.log(event)
        if (this.flag !== 0) {
          return;
        }
        let currentX = event.touches[0].clientX;
        let currentY = event.touches[0].clientY;
        let tx = currentX - this.lastX;
        let ty = currentY - this.lastY;
        this.mindex = -1;

        //左右方向滑动
        if (Math.abs(tx) > Math.abs(ty) && Math.abs(ty) < 10) {

          if (tx > 30) {
            console.log('left', tx, ty)
            this.current + 1 > 1 && this.toPrev()
            this.flag = 2;
          } else if (tx < -30) {
            console.log('right', tx, ty)
            this.flag = 1;
            this.current + 1 < this.total && this.toNext()
            //  this.getList();  //调用列表的方法
          }
        }

        //将当前坐标进行保存以进行下一次计算
        this.lastX = currentX;
        this.lastY = currentY;
      },
      handletouchstart: function(event) {
        // console.log(event)
        this.lastX = event.touches[0].clientX;
        this.lastY = event.touches[0].clientY;
      },
      handletouchend: function(event) {
        this.flag = 0;
      },
    }
  }
</script>

<style lang="scss">
  .exam {
    min-height: 100%;
    background-color: $bg_color;

    .scrollheight {
      max-height: calc(100vh - var(--status-bar-height) - 20vh);
    }

    .main {
      background-color: #ffffff;
      min-height: px2vh(850);
      font-size: px2vw(28);
      margin: px2vw(32);
    }

    .stem {
      padding: px2vw(16);
      font-size: px2vw(30);
    }

    .blue {
      color: $global-color;
    }

    .icon-lunwentimu {
      font-size: px2vw(40);
      margin-right: px2vw(10);
    }

    .fixed {
      @include fixed
    }

    .footer {
      // position: fixed;
      // bottom: 0;
      // width: 100%;
      // box-sizing: border-box;
      padding: px2vw(32);

      .prev {
        color: #00A2F7;
        background: #F5F6FA;
        border: 1px solid #00A2F7;
      }

      .btn {
        box-shadow: none;
      }

      .submit {
        background-color: #F55555;
      }
    }

  }
</style>
